#!/home/lin/software/miniconda3/envs/th1.11/bin/python
# -*- coding: utf-8 -*-
import open3d as o3d
import numpy as np
import copy

def draw_registration_result(source, target, transformation):
    source_temp = copy.deepcopy(source)
    target_temp = copy.deepcopy(target)
    source_temp.paint_uniform_color([1, 0.706, 0])
    target_temp.paint_uniform_color([0, 0.651, 0.929])
    source_temp.transform(transformation)
    o3d.visualization.draw_geometries([source_temp, target_temp],
                                      zoom=0.4459,
                                      front=[0.9288, -0.2951, -0.2242],
                                      lookat=[1.6784, 2.0612, 1.4451],
                                      up=[-0.3402, -0.9189, -0.1996])


source = o3d.io.read_point_cloud("../data/cloud_bin_0.pcd")
target = o3d.io.read_point_cloud("../data/cloud_bin_1.pcd")
o3d.visualization.draw_geometries([source, target])
threshold = 0.02
# 初始对准变换矩阵4x4
trans_init = np.asarray([[0.862, 0.011, -0.507, 0.5],
                         [-0.139, 0.967, -0.215, 0.7],
                         [0.487, 0.255, 0.835, -1.4],
                         [0.0, 0.0, 0.0, 1.0]])
# 上色与粗匹配转换
# draw_registration_result(source, target, trans_init)

# icp
# 该类TransformationEstimationPointToPoint提供用于计算点对点ICP目标函数的残差和雅可比矩阵的函数
# registration_icp运行直到收敛或达到最大迭代次数（默认为30）。
reg_p2p = o3d.pipelines.registration.registration_icp(
            source, target, threshold, trans_init,
            o3d.pipelines.registration.TransformationEstimationPointToPoint(),
            o3d.pipelines.registration.ICPConvergenceCriteria(max_iteration = 200)
)

print(reg_p2p)
print("Transformation is:")
print(reg_p2p.transformation)
draw_registration_result(source, target, reg_p2p.transformation)



# np是点云p的法向量。已经表明，点对面 ICP算法比点对点ICP算法具有更快的收敛速度。

reg_p2pl = o3d.pipelines.registration.registration_icp(
            source, target, threshold, trans_init,
            o3d.pipelines.registration.TransformationEstimationPointToPlane()
)

print(reg_p2pl)
print("Transformation is:")
print(reg_p2pl.transformation)
draw_registration_result(source, target, reg_p2pl.transformation)